﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Website.Models;

namespace Website.Controllers
{
    [Authorize(Roles = "User, Admin")]
    public class FileController : Controller
    {
        //
        // GET: /File/

        public ActionResult Open(Guid? ID)
        {
            if (ID.HasValue && ID.Value != Guid.Empty)
            {
                var crudFile = CRUDServiceProvider.WithCRUDService<CRUDServices.File>(client =>
                    {
                        CRUDServices.File file = new CRUDServices.File();
                        CRUDServices.FileQuery query = new CRUDServices.FileQuery()
                        {
                            Settings = new CRUDServices.SearchSettings(){ 
                                IDEquals = ID.Value
                            }
                        };
                        var res = client.Query(query) as CRUDServices.FileResult;
                        if (res != null && res.List.Any())
                        {
                            file = res.List[0];
                        }

                        return file;
                    });

                if (crudFile.ID == ID.Value)
                {
                    return File(crudFile.ContentData, crudFile.ContentType, crudFile.Name);
                }

            }
            return null;
        }

    }
}
